-1

我正在使用http://square.github.io/okhttp/的代码。我想要的是:我想通过发布请求从服务器获得响应。这是代码:

package com.codingpractise.www.officemanagement;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends Activity {

    TextView output;
    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


//      Initialize the TextView for vertical scrolling
        output = (TextView) findViewById(R.id.message);
        output.setMovementMethod(new ScrollingMovementMethod());

    }



    public void sendSalesData(View view) {
        try{
            if(isOnline()){
                //Net connection Ok
               // requestData("http://localhost:1234/track/process/data");

                String json = "{'winCondition':'HIGH_SCORE',"
                        + "'name':'Bowling',"
                        + "'round':4,"
                        + "'lastSaved':1367702411696,"
                        + "'dateStarted':1367702378785,"
                        + "'players':["
                        + "{'name':'" + "Sattar" + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
                        + "{'name':'" + "Santo" + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
                        + "]}";
                //String response = post("http://localhost:1234/track/process/data", json);
                MainActivity  thisObj = new MainActivity();

                String response = thisObj.post("http://localhost:1234/track/process/data", json);
               System.out.println(response);

               // String  response ="Fuck";
                output.setText(response);
            }
            else{
                output.setText("NO Internet connection!");
            }
        }
        catch (Exception e){
            output.setText(e.getMessage());
        }


    }

    protected boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }
      String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }
} 

单击按钮时,将执行 sendSalesData() 函数。在此功能中,我处理发布请求。当我单击此按钮时,响应应该在outputtextview 对象上可见。但我没有得到服务器的任何响应。

服务器响应只是简单的 php echo 代码:

echo 'response from server';

但是当我点击这个按钮时,我什么也得不到。我的代码有什么问题。

对不起,我的英语不好。我是 android 应用程序的初学者,所以如果我的问题不标准,我很抱歉。

4

3 回答 3

2

我已经使用它来使用 okHttp 发布数据。

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    RequestBody formBody = new FormEncodingBuilder()
        .add("search", "Jurassic Park")
        .build();
    Request request = new Request.Builder()
        .url("https://en.wikipedia.org/w/index.php")
        .post(formBody)
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }
于 2016-03-03T06:46:03.480 回答
1

要使用 OkHttp 发送 JSON 请求,请遵循以下方法 -

在您的活动或单独的活动中创建一个类 ResponseOKhttp

public class ResponseOKhttp

{
    OkHttpClient client = new OkHttpClient();

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    public String run(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

}

要使用上述类发送请求,只需将其实例化到您想要的位置即可。

ResponseOKhttp example = new ResponseOKhttp();

String response = null;
    try {
        response = example.run(url, json.toString());
    }
    catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.d("responsegot",response);
于 2016-03-03T06:47:13.440 回答
0

尝试使用 okhttp 发布数据

    public static JSONObject uploadImage() {

OkHttpClient client = new OkHttpClient();
            try {

                RequestBody req = new MultipartBody.builder().setType(MultipartBody.FORM).addFormDataPart("YOUR_KEY", "your value")
                        .addFormDataPart("YOUR_KEY","your value")).build();

                Request request = new Request.Builder()
                        .url("url")
                        .post(req)
                        .build();

                OkHttpClient client = new OkHttpClient();
                Response response = client.newCall(request).execute();

                Log.d("response", "uploadImage:"+response.body().string());

                return new JSONObject(response.body().string());

            } catch (UnknownHostException | UnsupportedEncodingException e) {
                Log.e(TAG, "Error: " + e.getLocalizedMessage());
            } catch (Exception e) {
                Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
            }
            return null;
        }
于 2016-03-03T06:43:09.463 回答