以前写ANDROID端与WEB服务器端交互用JSON,一直都是 参数名+JSON串,服务器端通过String jsonString=request.getParameter("jsonString"); 这样得到。
因为架构一直是自己设计并研发的,所以手机和服务器一直这样交无问题。今天接收到一个小项目,与其它服务器交互直接POST过去JSON字符串DATA数据(其实现在这种方式很主流了~~),试着看了一下,成功实现。代码如下:看来以后要改为这种交互了。不过以前那种方式,能实现发送JSON串的同时提交多个图片或声音等文件,还是不错的。
ANDROID客户端示例:
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
public class TestMain extends Activity {
/** Called when the activity is first created. */
public Context context;
private TextView textView1;
public static String URL = "http://192.168.3.75:8080/testr/test.jsp";
private DefaultHttpClient httpClient;
StringBuilder result = new StringBuilder();
private static final int TIMEOUT = 60;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HttpParams paramsw = createHttpParams();
httpClient = new DefaultHttpClient(paramsw);
HttpPost post = new HttpPost(URL);
try {
JSONObject json = new JSONObject();
json.put("email", "111@111.com");
json.put("password", "123456789");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse httpResponse = httpClient.execute(post);
int httpCode = httpResponse.getStatusLine().getStatusCode();
if (httpCode == HttpURLConnection.HTTP_OK&&httpResponse!=null) {
Header[] headers = httpResponse.getAllHeaders();
HttpEntity entity = httpResponse.getEntity();
Header header = httpResponse.getFirstHeader("content-type");
InputStream inputStream = entity.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String s;
while (((s = reader.readLine()) != null)) {
result.append(s);
}
reader.close();
JSONObject jsonObject = new JSONObject(result.toString());
int serverCode = jsonObject.getInt("serverCode");
String serverMsg = jsonObject.getString("serverMsg");
Log.v("url response", "serverCode="+serverCode);
Log.v("url response", "serverMsg="+serverMsg);
UIUtil.alert(TestMain.this, "消息",jsonObject.toString());
} else {
textView1.setText("Error Response" + httpResponse.getStatusLine().toString());
}
} catch (UnsupportedEncodingException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
}
}
});
}
public static final HttpParams createHttpParams() {
final HttpParams params = new BasicHttpParams();
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);
HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192 * 5);
return params;
}
}服务器端JSP获取方法:
<%@ page contentType="text/json; charset=utf-8"%><%@ page language="java"%><%@ page import="java.util.*,java.io.*,net.sf.json.*" %><%
//String email=request.getParameter("email");
//System.out.println("email="+email);
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
json.append(line);
}
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("client json data="+json);
JSONObject jsonObj = JSONObject.fromObject(json.toString());
String youremail=jsonObj.getString("email");
String password=jsonObj.getString("password");
JSONObject resp = new JSONObject();
resp.accumulate("serverCode",200);
resp.accumulate("serverMsg","your email="+youremail+",and password="+password);
out.print(resp.toString());
%>
本文介绍了一种Android客户端与服务器端使用JSON进行数据交换的方法,包括客户端如何构造JSON请求及服务器端如何解析JSON数据。
2066

被折叠的 条评论
为什么被折叠?



