无法通过OkHttp获得回复

时间:2016-03-03 06:34:17

标签: android okhttp3

我正在使用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()函数。在这个函数中我处理发布请求。当我单击此按钮时,响应应显示在output textview对象上。但我没有从服务器得到任何回应。

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

echo 'response from server';

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

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

3 个答案:

答案 0 :(得分:1)

我使用它来使用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());
  }

答案 1 :(得分: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);

答案 2 :(得分: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;
        }