1、首先输入代码
public void SendByHttpClient(final String id, final String pw){
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpclient=new DefaultHttpClient()
HttpPost httpPost=new HttpPost("http://web应用部署服务器上的IP地址:/HttpClientDemo/Login")//服务器地址,指向Servlet
List<NameValuePair>params=new ArrayList<NameValuePair>()//将id和pw装入list
params.add(new BasicNameValuePair("ID",id))
params.add(new BasicNameValuePair("PW",pw))
final UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8")//以UTF-8格式发送
httpPost.setEntity(entity)
HttpResponse httpResponse= httpclient.execute(httpPost)
if(httpResponse.getStatusLine().getStatusCode()==200)//在200毫秒之内接收到返回值
2、然后再输入下方的代码:
{
HttpEntity entity=httpResponse.getEntity()
String response=EntityUtils.toString(entity1, "utf-8")//以UTF-8格式解析
Message message=new Message()
message.what=USER_LOGIN
message.obj=response
handler.sendMessage(message)使用Message传递消息给线程
}
}
catch (Exception e) {
e.printStackTrace()
}
}
}).start()
}3、最终,测试结果图,如下:
服务器端生成JSON:
使用HttpURLConnection连接,通过JSON格式传递对象数据
URL url = new URL(urlpath)HttpURLConnection conn = (HttpURLConnection) url.openConnection()
InputStream inStream = conn.getInputStream()
ByteArrayOutputStream outStream = new ByteArrayOutputStream()
byte[] data = new byte[1024]
int len = 0
while ((len = inStream.read(data)) != -1) {
outStream.write(data, 0, len)
System.out.println(len)
}
inStream.close()
byte[] rlt = outStream.toByteArray()
return new String(rlt)
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)