我正在使用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 应用程序的初学者,所以如果我的问题不标准,我很抱歉。