JAVA发送http(s)请求

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">第一种实现方法:不需要任何第三放jar包,只需要sun基础包rt.jar即可!!!</span>

String urlStr = "http://api.map.baidu.com/geodata/v3/poi/update";

String input="ak=3sd234&name=sdfl&images=/images/logo.jpg";

/**
 * 提交http post请求
 * @param urlStr 请求地址
 * @param input 请求参数
 * @return json结果
 */
public String sendURLPost(String urlStr, String input){
    StringBuffer strBuf = new StringBuffer();
    try{
        URL url = new URL(urlStr);
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setAllowUserInteraction(false);         
        con.setUseCaches(false); 
        con.setRequestProperty("Accept-Charset", "GBK");    //GBK
        BufferedOutputStream bufOutPut = new BufferedOutputStream(con.getOutputStream());
        byte[] bdat = input.getBytes("UTF-8");//解决中文乱码问题
        bufOutPut.write(bdat, 0, bdat.length);
        bufOutPut.flush();
        BufferedInputStream inp = new BufferedInputStream(con.getInputStream());
        InputStreamReader in = new InputStreamReader(inp,Charset.forName("GBK"));
        BufferedReader bufReador = new BufferedReader(in);
        String tempStr = "";
        while (tempStr!= null) {
            strBuf.append(tempStr);
            tempStr = bufReador.readLine();
        }
        return strBuf.toString();
    }
    catch (Exception e) {
    	e.printStackTrace();
    }
	return null;
}

第二种实现方法:需要用到第三方jar包,httpclient-4.1.2.jar

public String templateSMS(String accountSid, String authToken,
		String appId, String templateId, String to, String param) {
	String result = "";
	DefaultHttpClient httpclient = new DefaultHttpClient();
	try {
		//MD5加密(自定义加密工具)
		EncryptUtil encryptUtil = new EncryptUtil();
		//时间戳
		String timestamp = DateUtil.dateToStr(new Date(),DateUtil.DATE_TIME_NO_SLASH);// 时间戳
		//验证字符串(下面的方法)
		String signature =getSignature(accountSid,authToken,timestamp,encryptUtil);
		//构造请求URL内容
		String url = getStringBuffer().append("/").append(version)
				.append("/Accounts/").append(accountSid)
				.append("/Messages/templateSMS")
				.append("?sig=").append(signature).toString();
		/**发短信的模板类domain对象**/
		TemplateSMS templateSMS=new TemplateSMS();
		templateSMS.setAppId(appId);     //开发者ID
		templateSMS.setTemplateId(templateId); //短信模板ID
		templateSMS.setTo(to);          //目的手机号码
		templateSMS.setParam(param);    //验证码
		/**
		 * Gson的作用为:把domain对象转换成json格式,如果domain对象属性为null或者"",就不放里面
		 */
		Gson gson = new Gson();
		String body = gson.toJson(templateSMS);
		body="{\"templateSMS\":"+body+"}";
		logger.info(body);
		//调用POST方法发送请求
		HttpResponse response=post("application/json",accountSid, authToken, timestamp, url, httpclient, encryptUtil, body);
		//对请求返回的信息做解析处理
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			result = EntityUtils.toString(entity, "UTF-8");
		}
		EntityUtils.consume(entity);
	} catch (Exception e) {
		e.printStackTrace();
	} finally{
		// 关闭连接
		httpclient.getConnectionManager().shutdown();
	}
	return result;
}

/**
 * 用自定义密码工具类,对开发者id,开发者秘钥,时间戳进行md5加密
 * @param accountSid 对开发者id
 * @param authToken 开发者秘钥
 * @param timestamp 时间戳
 * @param encryptUtil 自定义加密工具类
 * @return 验证字符串
 * @throws Exception
 */
public String getSignature(String accountSid, String authToken,String timestamp,EncryptUtil encryptUtil) throws Exception{
	String sig = accountSid + authToken + timestamp;
	String signature = encryptUtil.md5Digest(sig);
	return signature;
}

public HttpResponse post(String cType,String accountSid,String authToken,String timestamp,String url,DefaultHttpClient httpclient,EncryptUtil encryptUtil,String body) throws Exception{
	//构建http请求
	HttpPost httppost = new HttpPost(url);
	httppost.setHeader("Accept", cType);
	httppost.setHeader("Content-Type", cType+";charset=utf-8");
	String src = accountSid + ":" + timestamp;
	//base64编码
	String auth = encryptUtil.base64Encoder(src);
	httppost.setHeader("Authorization", auth);
	/**构建http请求实体内容*/
	BasicHttpEntity requestBody = new BasicHttpEntity();
	requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
	requestBody.setContentLength(body.getBytes("UTF-8").length);
	httppost.setEntity(requestBody);
	//执行客户端请求
	HttpResponse response = httpclient.execute(httppost);
	return response;
}

public HttpResponse get(String cType,String accountSid,String authToken,String timestamp,String url,DefaultHttpClient httpclient,EncryptUtil encryptUtil) throws Exception{
	HttpGet httpget = new HttpGet(url);
	httpget.setHeader("Accept", cType);//
	httpget.setHeader("Content-Type", cType+";charset=utf-8");
	String src = accountSid + ":" + timestamp;
	String auth = encryptUtil.base64Encoder(src);
	httpget.setHeader("Authorization",auth);
	HttpResponse response = httpclient.execute(httpget);
	return response;
}

加密工具类代码:

import java.security.MessageDigest;  
import sun.misc.BASE64Decoder;  
import sun.misc.BASE64Encoder;  

public class EncryptUtil {  

    private static final String UTF8 = "utf-8";  
  
    /** 
     * MD5数字签名 
     * @param src 
     * @return 
     * @throws Exception 
     */  
    public String md5Digest(String src) throws Exception {  
       // 定义数字签名方法, 可用:MD5, SHA-1  
       MessageDigest md = MessageDigest.getInstance("MD5");  
       byte[] b = md.digest(src.getBytes(UTF8));  
       return this.byte2HexStr(b);  
    }  
      
    /** 
     * BASE64编码
     * @param src 
     * @return 
     * @throws Exception 
     */  
    public String base64Encoder(String src) throws Exception {  
        BASE64Encoder encoder = new BASE64Encoder();  
        return encoder.encode(src.getBytes(UTF8));  
    }  
      
    /** 
     * BASE64解码
     * @param dest 
     * @return 
     * @throws Exception 
     */  
    public String base64Decoder(String dest) throws Exception {  
        BASE64Decoder decoder = new BASE64Decoder();  
        return new String(decoder.decodeBuffer(dest), UTF8);  
    }  
      
    /** 
     * 字节数组转化为大写16进制字符串 
     * @param b 
     * @return 
     */  
    private String byte2HexStr(byte[] b) {  
        StringBuilder sb = new StringBuilder();  
        for (int i = 0; i < b.length; i++) {  
            String s = Integer.toHexString(b[i] & 0xFF);  
            if (s.length() == 1) {  
                sb.append("0");  
            }  
            sb.append(s.toUpperCase());  
        }  
        return sb.toString();  
    }  
} 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送WebSocket请求可以使用Java API中提供的WebSocketClient类。下面是一个简单的示例: ```java import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; import org.eclipse.jetty.websocket.client.WebSocketClient; public class WebSocketExample { public static void main(String[] args) throws Exception { String destUri = "ws://localhost:8080/mywebsocket"; WebSocketClient client = new WebSocketClient(); SimpleEchoSocket socket = new SimpleEchoSocket(); try { client.start(); URI echoUri = new URI(destUri); ClientUpgradeRequest request = new ClientUpgradeRequest(); client.connect(socket, echoUri, request); System.out.printf("Connecting to : %s%n", echoUri); socket.awaitClose(5, TimeUnit.SECONDS); } finally { client.stop(); } } private static class SimpleEchoSocket extends WebSocketAdapter { private final CountDownLatch closeLatch; public SimpleEchoSocket() { this.closeLatch = new CountDownLatch(1); } @Override public void onWebSocketClose(int statusCode, String reason) { System.out.printf("Connection closed: %d - %s%n", statusCode, reason); this.closeLatch.countDown(); } @Override public void onWebSocketConnect(Session session) { System.out.printf("Connected to server: %s%n", session.getRemoteAddress().getHostName()); try { session.getRemote().sendString("Hello, World!"); } catch (IOException e) { e.printStackTrace(); } } @Override public void onWebSocketText(String message) { System.out.printf("Received message: %s%n", message); } public void awaitClose(int duration, TimeUnit unit) throws InterruptedException { this.closeLatch.await(duration, unit); } } } ``` 在上面的示例中,我们使用了Jetty WebSocket API,它提供了WebSocketClient类。我们创建了一个WebSocketClient对象,并创建了一个SimpleEchoSocket对象。然后,我们使用client.connect()方法连接到WebSocket服务器。最后,我们使用socket.awaitClose()方法等待WebSocket连接关闭。在SimpleEchoSocket中,我们实现了一些WebSocket事件的处理方法,如onWebSocketConnect()、onWebSocketText()和onWebSocketClose()。在onWebSocketConnect()方法中,我们发送了一条Hello, World!消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值