您的位置:首页 > 理论基础 > 计算机网络

用Java的HttpClient写一个简单的http请求和返回

2015-08-11 20:47 489 查看


用Java的HttpClient写一个简单的http请求和返回

博客分类:

webgame



Java代码


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;



import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;



public class TTT

{



/**

* @param args

* @throws IOException

* @throws ClientProtocolException

*/

public static void main(String[] args) throws ClientProtocolException, IOException

{

// 创建HttpClient实例

HttpClient httpclient = new DefaultHttpClient();

// 创建Get方法实例

HttpGet httpgets = new HttpGet("http://127.0.0.1/testhttp.php?username=yonghuming");

HttpResponse response = httpclient.execute(httpgets);

HttpEntity entity = response.getEntity();

if (entity != null) {

InputStream instreams = entity.getContent();

String str = convertStreamToString(instreams);

System.out.println("Do something");

System.out.println(str);

// Do not need the rest

httpgets.abort();

}

}



public static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

StringBuilder sb = new StringBuilder();



String line = null;

try {

while ((line = reader.readLine()) != null) {

sb.append(line + "\n");

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return sb.toString();

}



}





HTTP服务器的testhttp.php内容如下

Php代码


<?php

if ($_GET['username'])

{

$dt["username"] = $_GET['username'];

echo json_encode($dt);

}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: