android post用对象流,Android*无封装*使用urlconnection和json发送http post请求

客户端:

***

*HttpURLConnection连接服务器

*

*1、通过后台得到sessionID

*2、检查MAC地址是否正确

*3、处理从服务器读取的JSON对象

*4、从服务器读取对象

*5、得到对象输出流

*6、设置HttpURLConnection参数

*

* @author "zhaohaiyang"

*@version 版本号 2010-1-14

下午02:01:41

*@see

相关类/方法

**/

public class ConUtils

{

public static String receiveSessionID(String[] parameters, String[]

values)

{

String tempSessionId = "";// SessionID

URL url = null;//

请求处理的Servlet

ObjectOutputStream

objOutputStrm = null;// 对象输出流

InputStream inStrm = null;//

得到HttpURLConnection的输入流

HttpURLConnection httpUrlConnection = null;

//

设置HttpURLConnection参数

httpUrlConnection =

setURLConnectionProperties(url);

//

得到对象输出流

objOutputStrm = getObjOutStream(httpUrlConnection);

JSONObject

obj = new JSONObject();

for (int i = 0; i < parameters.length; i++)

{

obj.put(parameters[i], values[i]);

}

// 向对象输出流写出数据,这些数据将存到内存缓冲区中

objOutputStrm.writeObject(obj.toString());

// 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream)

objOutputStrm.flush();

// 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中,

// 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器

// objOutputStrm.close();

//

调用HttpURLConnection连接对象的getInputStream()函数,

// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。

inStrm = httpUrlConnection.getInputStream(); //

<===注意,实际发送请求的代码段就在这里

//

上边的httpConn.getInputStream()方法已调用,本次HTTP请求已结束,下边向对象输出流的输出已无意义,

// 既使对象输出流没有调用close()方法,下边的操作也不会向对象输出流写入任何数据.

// 因此,要重新发送数据时需要重新创建连接、重新设参数、重新创建流对象、重新写数据、

// 重新发送数据(至于是否不用重新这些操作需要再研究)

// objOutputStrm.writeObject(new String(""));

// httpUrlConnection.getInputStream();

//

从服务器读取对象

Object inObj = readObjectFromServer(inStrm);

// 处理从服务器读取的JSON对象

tempSessionId = doJsonObjectFromServerForSesId(tempSessionId,

inObj);

}

catch (MalformedURLException e)

{

e.printStackTrace();

}

catch (ProtocolException e)

{

e.printStackTrace();

}

catch (IOException e)

{

e.printStackTrace();

}

catch (JSONException e)

{

e.printStackTrace();

}

finally

{

try

{

if (objOutputStrm != null)

{

objOutputStrm.close();

}

}

catch (IOException e)

{

e.printStackTrace();

}

try

{

if (inStrm != null)

{

inStrm.close();

}

}

catch (IOException e)

{

e.printStackTrace();

}

}

return tempSessionId;

}

public static boolean checkMac(String mac)

{

URL url = null;//

请求处理的Servlet

boolean flag = false;//

MAC地址是否正确

ObjectOutputStream

objOutputStrm = null;// 对象输出流

InputStream inStrm = null;//

得到HttpURLConnection的输入流

HttpURLConnection httpUrlConnection = null;

try

{

url = new URL("http://192.168.18.109:8080/jj_erp/checkMac");

//

设置HttpURLConnection参数

httpUrlConnection =

setURLConnectionProperties(url);

//

得到对象输出流

objOutputStrm = getObjOutStream(httpUrlConnection);

JSONObject

obj = new JSONObject();

obj.put("mac", mac);

// 向对象输出流写出数据,这些数据将存到内存缓冲区中

objOutputStrm.writeObject(obj.toString());

// 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream)

objOutputStrm.flush();

// 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中,

// 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器

// objOutputStrm.close();

//

调用HttpURLConnection连接对象的getInputStream()函数,

// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。

inStrm = httpUrlConnection.getInputStream(); //

<===注意,实际发送请求的代码段就在这里

//

上边的httpConn.getInputStream()方法已调用,本次HTTP请求已结束,下边向对象输出流的输出已无意义,

// 既使对象输出流没有调用close()方法,下边的操作也不会向对象输出流写入任何数据.

// 因此,要重新发送数据时需要重新创建连接、重新设参数、重新创建流对象、重新写数据、

// 重新发送数据(至于是否不用重新这些操作需要再研究)

// objOutputStrm.writeObject(new String(""));

// httpUrlConnection.getInputStream();

//

从服务器读取对象

Object inObj = readObjectFromServer(inStrm);

// 处理从服务器读取的JSON对象

flag = doJsonObjectFromServer(flag, inObj);

}

catch (MalformedURLException e)

{

e.printStackTrace();

}

catch (IOException e)

{

e.printStackTrace();

}

catch (JSONException e)

{

e.printStackTrace();

}

finally

{

}

return flag;

}

private static boolean

doJsonObjectFromServer(boolean flag, Object inObj)

throws JSONException

{

// 做非空处理

if (inObj != null)

{

// 根据得到的序列化对象 构建JSON对象

JSONObject injson = new JSONObject(inObj.toString());

// 拿到JSON对象中 对应key的值

String getStr = injson.getString("returnstring");

if (getStr.equals("true"))

{

flag = true;

}

}

return flag;

}

private static String

doJsonObjectFromServerForSesId(String tempSessionID,

Object inObj) throws JSONException

{

// 做非空处理

if (inObj != null)

{

// 根据得到的序列化对象 构建JSON对象

JSONObject injson = new JSONObject(inObj.toString());

// 拿到JSON对象中 对应key的值

tempSessionID = injson.getString("sessionID");

}

return tempSessionID;

}

private static Object

readObjectFromServer(InputStream inStrm)

throws IOException

{

ObjectInputStream objInStream; // 输入流 从服务器读取JSON对象

objInStream = new ObjectInputStream(inStrm);// 输入流

从服务器读取JSON对象

Object inObj = null;

try

{

inObj = objInStream.readObject();// 读取对象

}

catch (ClassNotFoundException e)

{

e.printStackTrace();

}

return inObj;

}

private static ObjectOutputStream

getObjOutStream(

HttpURLConnection httpUrlConnection) throws IOException

{

OutputStream outStrm;// 得到HttpURLConnection的输出流

ObjectOutputStream objOutputStrm;// 对象输出流

// 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,

// 所以在开发中不调用上述的connect()也可以)。

outStrm = httpUrlConnection.getOutputStream();

//

现在通过输出流对象构建对象输出流对象,以实现输出可序列化的对象。

// 使用JSON传值

objOutputStrm = new ObjectOutputStream(outStrm);

return objOutputStrm;

}

private static HttpURLConnection setURLConnectionProperties(URL

url)

throws IOException, ProtocolException

{

HttpURLConnection httpUrlConnection;

URLConnection rulConnection = url.openConnection();//

此处的urlConnection对象实际上是根据URL的

// 请求协议(此处是http)生成的URLConnection类

// 的子类HttpURLConnection,故此处最好将其转化

// 为HttpURLConnection类型的对象,以便用到

// HttpURLConnection更多的API.如下:

httpUrlConnection = (HttpURLConnection) rulConnection;

// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在

// http正文内,因此需要设为true, 默认情况下是false;

httpUrlConnection.setDoOutput(true);

// 设置是否从httpUrlConnection读入,默认情况下是true;

httpUrlConnection.setDoInput(true);

// Post 请求不能使用缓存

httpUrlConnection.setUseCaches(false);

//

设定传送的内容类型是可序列化的java对象

// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)

// httpUrlConnection.setRequestProperty("Content-type",

// "application/x-java-serialized-object");

// httpUrlConnection

.setRequestProperty("Content-type", "application/json");

// 设定请求的方法为"POST",默认是GET

httpUrlConnection.setRequestMethod("POST");

try

{

// 连接,从上述至此的配置必须要在connect之前完成,

httpUrlConnection.connect();

httpUrlConnection.setConnectTimeout(1);

httpUrlConnection.setReadTimeout(1);

}

catch (ConnectException e1)

{

if (e1.getMessage().equals("Connection refused: connect"))

{

JOptionPane.showMessageDialog(null, "连接超时");

System.exit(0);

}

}

return httpUrlConnection;

}

public static void main(String[] args)

{

if (checkMac("40-61-86-69-82-E2"))

{

System.out.println("mac地址校验成功");

}

else

{

System.out.println("mac地址校验失败");

}

}

}

服务器端:

checkMac.java

public class CheckMac extends HttpServlet

{

private static final

long serialVersionUID = 1L;

private

String returnstring =

"false";

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse

resp)

throws ServletException, IOException

{

InputStream inStream = req.getInputStream();

ObjectInputStream objInStream = new

ObjectInputStream(inStream);

Object obj = null;

try

{

obj = objInStream.readObject();

}

catch (ClassNotFoundException e1)

{

e1.printStackTrace();

}

JSONObject json = null;

String mac = "";

JSONObject outjson = new JSONObject();

try

{

if (obj != null)

{

json = new JSONObject(obj.toString());

mac = json.getString("mac");

if

(mac.equals("40-61-86-69-82-E2"))

{

returnstring = "true";

}

}

}

catch (JSONException e)

{

e.printStackTrace();

}

try

{

outjson.put("returnstring", returnstring);

}

catch (JSONException e)

{

e.printStackTrace();

}

resp.setContentType("text/html;charset=utf-8");

OutputStream out = resp.getOutputStream();

ObjectOutputStream objOutputStrm = new

ObjectOutputStream(out);

objOutputStrm.writeObject(outjson.toString());

objOutputStrm.flush();

objOutputStrm.close();

}

LoginValidate.java

private

String dept =

""; // 部门

private

String name =

""; // 姓名

private

String pass =

""; // 密码

private

String mac =

""; // MAC地址

private

String ip =

""; // IP地址

private

String sessionID =

"";

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse

resp)

throws ServletException, IOException

{

InputStream inStream = req.getInputStream();

ObjectInputStream objInStream = new

ObjectInputStream(inStream);

Object obj = null;

try

{

obj = objInStream.readObject();

}

catch (ClassNotFoundException e1)

{

e1.printStackTrace();

}

JSONObject json = null;

JSONObject outjson = new JSONObject();

try

{

if (obj != null)

{

json = new JSONObject(obj.toString());

if (json != null)

{

dept = json.getString("dept");

name = json.getString("name");

pass = json.getString("pass");

mac = json.getString("mac");

ip = json.getString("ip");

}

}

}

catch (JSONException e)

{

e.printStackTrace();

}

if (validateInfo())

{

// HttpSession

session = req.getSession(true);

// sessionID =

session.getId();

sessionID = "sessionid";

}

// 把sessionID放入JSON中

try

{

outjson.put("sessionID", sessionID);

}

catch (JSONException e)

{

e.printStackTrace();

}

//

将sessionID以JSON方式发送到客户端

resp.setContentType("text/html;charset=utf-8");

OutputStream out = resp.getOutputStream();

ObjectOutputStream objOutputStrm = new

ObjectOutputStream(out);

objOutputStrm.writeObject(outjson.toString());

objOutputStrm.flush();

objOutputStrm.close();

}

private boolean validateInfo()

{

return true;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java发送HTTP请求,并且以JSON格式发送POST请求的示例如下: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpRequestExample { public static void main(String[] args) throws IOException { // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpPost对象,设置URL HttpPost httpPost = new HttpPost("http://example.com/api/endpoint"); // 设置请求httpPost.setHeader("Content-Type", "application/json"); // 设置请求体 String jsonBody = "{\"name\":\"John\",\"age\":30}"; StringEntity requestEntity = new StringEntity(jsonBody, ContentType.APPLICATION_JSON); httpPost.setEntity(requestEntity); // 发送请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); try { // 获取响应实体 HttpEntity entity = response.getEntity(); if (entity != null) { // 将响应实体转为字符串,并打印输出 String result = EntityUtils.toString(entity); System.out.println(result); } } finally { // 关闭响应和HttpClient response.close(); httpClient.close(); } } } ``` 以上代码示例中,使用了Apache HttpClient库来发送HTTP请求。首先创建一个 `HttpPost` 对象并设置URL为目标URL。然后设置请求头,这里使用 `application/json` 表示请求体的类型为JSON格式。接下来创建一个 `StringEntity` 对象作为请求体,传入要发送JSON字符串和请求体的类型。然后将请求体设置到 `HttpPost` 对象中。 最后,通过调用 `httpClient.execute(httpPost)` 方法来发送请求并获取响应。如果响应实体不为空,则将其转为字符串并打印输出。最后记得关闭响应和 `HttpClient` 对象。 ### 回答2: Java发送HTTP请求使用JSON格式进行POST请求的方法如下所示: 首先,我们需要通过URL和URLConnection对象建立HTTP连接。 ```java String url = "http://example.com/api/endpoint"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); ``` 接下来,我们需要设置请求方法为POST,并设置请求头的Content-Type为application/json。 ```java con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); ``` 然后,我们需要构建JSON数据并将其作为请求发送。 ```java String jsonBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(jsonBody); wr.flush(); wr.close(); ``` 最后,我们可以通过读取HTTP响应获取服务器返回的数据。 ```java int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); ``` 以上就是使用Java发送HTTP请求使用JSON格式进行POST请求的基本过程。您可以根据实际情况进行适当的修改和扩展,例如添加请求头信息、处理错误响应等。 ### 回答3: 在Java中发送HTTP请求并且以JSON格式发送POST请求的步骤如下: 1. 导入相关类库:在代码中导入java.net包下的HttpURLConnection类和相关IO类,以及org.json包中的JSON对象类。 2. 建立连接:使用URL类创建一个URL对象,将请求的URL作为参数传入。然后使用URL对象的openConnection()方法创建一个HttpURLConnection对象。 3. 设置请求属性:通过调用HttpURLConnection对象的setRequestMethod()方法,设置请求的方法为POST。同时通过setRequestProperty()方法设置请求头的Content-Type属性为application/json。 4. 打开连接:调用HttpURLConnection对象的connect()方法,建立与请求的URL的连接。 5. 创建JSON对象并写入数据:通过创建一个JSONObject对象,并且调用其put()方法向JSON对象中添加需要发送的数据。 6. 发送请求:通过调用HttpURLConnection对象的getOutputStream()方法获取输出,将JSON对象转换为字符串,然后转换为字节数组,最后通过写入输出发送请求。 7. 获取响应:通过调用HttpURLConnection对象的getResponseCode()方法获取响应码,判断请求是否成功。若成功,则通过调用getInputStream()方法获取输入,然后通过IO读取输入中的数据。 8. 关闭连接:关闭输入、输出和连接。 完整的示例代码如下: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class HttpJsonPostExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com/api"); // 替换为请求的URL // 创建HttpURLConnection对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求属性 connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); // 打开连接 connection.connect(); // 创建JSON对象 JSONObject jsonRequest = new JSONObject(); jsonRequest.put("key1", "value1"); jsonRequest.put("key2", "value2"); // 发送请求 OutputStream outputStream = connection.getOutputStream(); outputStream.write(jsonRequest.toString().getBytes()); outputStream.flush(); // 获取响应 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理响应 JSONObject jsonResponse = new JSONObject(response.toString()); System.out.println(jsonResponse.toString()); } else { System.out.println("请求失败"); } // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这是一个基本的示例,只是通过调用println()方法打印出响应的JSON数据。实际应用中,你可以根据需求来处理响应数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值