㈠ java如何调用对方http接口 新手虚心求教
importjava.io.BufferedReader;
importjava.io.DataOutputStream;
importjava.io.InputStreamReader;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.net.URLEncoder;
publicclassDemoTest1{
publicstaticfinalStringGET_URL="http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
//publicstaticfinalStringPOST_URL="http://112.4.27.9/mall-back/if_user/store_list";
//妙兜测试接口
publicstaticfinalStringPOST_URL="http://121.40.204.191:8180/mdserver/service/installLock";
/**
*接口调用GET
*/
(){
try{
URLurl=newURL(GET_URL);//把字符串转换为URL请求地址
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//打开连接
connection.connect();//连接会话
//获取输入流
BufferedReaderbr=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){//循环读取流
sb.append(line);
}
br.close();//关闭流
connection.disconnect();//断开连接
System.out.println(sb.toString());
}catch(Exceptione){
e.printStackTrace();
System.out.println("失败!");
}
}
/**
*接口调用POST
*/
(){
try{
URLurl=newURL(POST_URL);
//将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();//此时cnnection只是为一个连接对象,待连接中
//设置连接输出流为true,默认false(post请求是以流的方式隐式的传递参数)
connection.setDoOutput(true);
//设置连接输入流为true
connection.setDoInput(true);
//设置请求方式为post
connection.setRequestMethod("POST");
//post请求缓存设为false
connection.setUseCaches(false);
//设置该HttpURLConnection实例是否自动执行重定向
connection.setInstanceFollowRedirects(true);
//设置请求头里面的各个属性(以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
//application/x-javascripttext/xml->xml数据application/x-javascript->json对象application/x-www-form-urlencoded->表单数据
//;charset=utf-8必须要,不然妙兜那边会出现乱码【★★★★★】
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
//建立连接(请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
connection.connect();
//创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
DataOutputStreamdataout=newDataOutputStream(connection.getOutputStream());
Stringapp_key="app_key="+URLEncoder.encode("","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringagt_num="&agt_num="+URLEncoder.encode("10111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringpid="&pid="+URLEncoder.encode("BLZXA150401111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringdepartid="&departid="+URLEncoder.encode("10007111","utf-8");//已修改【改为错误数据,以免信息泄露】
Stringinstall_lock_name="&install_lock_name="+URLEncoder.encode("南天大门","utf-8");
Stringinstall_address="&install_address="+URLEncoder.encode("北京育新","utf-8");
Stringinstall_gps="&install_gps="+URLEncoder.encode("116.350888,40.011001","utf-8");
Stringinstall_work="&install_work="+URLEncoder.encode("小李","utf-8");
Stringinstall_telete="&install_telete="+URLEncoder.encode("13000000000","utf-8");
Stringintall_comm="&intall_comm="+URLEncoder.encode("一切正常","utf-8");
//格式parm=aaa=111&bbb=222&ccc=333&ddd=444
Stringparm=app_key+agt_num+pid+departid+install_lock_name+install_address+install_gps+install_work+install_telete+intall_comm;
//将参数输出到连接
dataout.writeBytes(parm);
//输出完成后刷新并关闭流
dataout.flush();
dataout.close();//重要且易忽略步骤(关闭流,切记!)
//System.out.println(connection.getResponseCode());
//连接发起请求,处理服务器响应(从连接获取到输入流并包装为bufferedReader)
BufferedReaderbf=newBufferedReader(newInputStreamReader(connection.getInputStream(),"UTF-8"));
Stringline;
StringBuildersb=newStringBuilder();//用来存储响应数据
//循环读取流,若不到结尾处
while((line=bf.readLine())!=null){
//sb.append(bf.readLine());
sb.append(line).append(System.getProperty("line.separator"));
}
bf.close();//重要且易忽略步骤(关闭流,切记!)
connection.disconnect();//销毁连接
System.out.println(sb.toString());
}catch(Exceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
//httpURLConectionGET();
httpURLConnectionPOST();
}
}
㈡ java调用基于http+post+xml接口
1、直接用servlet就可以了,request.getInputStream(),然后解析xml,然后你的业务操作,组装XML,response.getOutputStream()写出去就OK了。
但这个性能低,而且还要依赖web容器。
2、socket实现http协议,把HTTP协议好好看看,自己解析(其实就是字符串的操作哦)。
3、你要是只做客户端的话可以用httpClient,几行代码搞定了
㈢ javaweb、jsp中调用外部的http接口
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www..com/query.jsp?param1=value2¶m2=value2");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
㈣ java如何使用http方式调用第三方接口最好有代码~谢谢
星号是IP地址和端口号
public class HttpUtil {
private final static Log log = LogFactory.getLog(HttpUtil.class);
public static String doHttpOutput(String outputStr,String method) throws Exception {
Map map = new HashMap();
String URL = "http://****/interface/http.php" ;
String result = "";
InputStream is = null;
int len = 0;
int tmp = 0;
OutputStream output = null;
BufferedOutputStream objOutput = null;
String charSet = "gbk";
System.out.println("URL of fpcy request");
System.out.println("=============================");
System.out.println(URL);
System.out.println("=============================");
HttpURLConnection con = getConnection(URL);
try {
output = con.getOutputStream();
objOutput = new BufferedOutputStream(output);
objOutput.write(outputStr.getBytes(charSet));
objOutput.flush();
output.close();
objOutput.close();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
is = con.getInputStream();
int dataLen = is.available();
int retry = 5;
while (dataLen == 0 && retry > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
dataLen = is.available();
retry--;
log.info("未获取到任何数据,尝试重试,当前剩余次数" + retry);
}
log.info("获取到报文单位数据长度:" + dataLen);
byte[] bytes = new byte[dataLen];
while ((tmp = is.read()) != -1) {
bytes[len++] = (byte) tmp;
if (len == dataLen) {
dataLen = bytes.length + dataLen;
byte[] newbytes = new byte[dataLen];
for (int i = 0; i < bytes.length; i++) {
newbytes[i] = bytes[i];
}
bytes = newbytes;
}
}
result = new String(bytes, 0, len, charSet);
} else {
String responseMsg = "调用接口失败,返回错误信息:" + con.getResponseMessage() + "(" + responseCode + ")";
System.out.println(responseMsg);
throw new Exception(responseMsg);
}
} catch (IOException e2) {
log.error(e2.getMessage(), e2);
throw new Exception("接口连接超时!,请检查网络");
}
con.disconnect();
System.out.println("=============================");
System.out.println("Contents of fpcy response");
System.out.println("=============================");
System.out.println(result);
Thread.sleep(1000);
return result;
}
private static HttpURLConnection getConnection(String URL) throws Exception {
Map map = new HashMap();
int rTimeout = 15000;
int cTimeout = 15000;
String method = "";
method = "POST";
boolean useCache = false;
useCache = false;
HttpURLConnection con = null;
try {
con = (HttpURLConnection) new URL(URL).openConnection();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new Exception("URL不合法!");
}
try {
con.setRequestMethod(method);
} catch (ProtocolException e) {
log.error(e.getMessage(), e);
throw new Exception("通信协议不合法!");
}
con.setConnectTimeout(cTimeout);
con.setReadTimeout(rTimeout);
con.setUseCaches(useCache);
con.setDoInput(true);
con.setDoOutput(true);
log.info("当前连接信息: URL:" + URL + "," + "Method:" + method
+ ",ReadTimeout:" + rTimeout + ",ConnectTimeOut:" + cTimeout
+ ",UseCaches:" + useCache);
return con;
}
public static void main(String[] args) throws Exception {
String xml="<?xml version=\"1.0\" encoding=\"GBK\" ?><document><txcode>101</txcode><netnumber>100001</netnumber>.........</document>";
response=HttpUtil.doHttpOutput(xml, "post");
JSONObject json= JSONObject.parseObject(response);
String retcode=json.getString("retcode");
调用这个类就能获得返回的参数。。over.
}
}
}
㈤ java中怎么调用http接口
方法:祥侍只要New一个Map,然后把要传递的参数以键值毕宴肆手轿对的形式存入Map即可。
private void Example() {
String url =地址;
Map<String, String> param = new HashMap<String, String>();
p.put("ParamName", "ParamValue");
String html = this.visitURL(url, param);
}
㈥ java http调用接口书写
rest接口的话可以使用
RestTemplate
Stringuri="http://example.com/hotels/1/bookings";
PostMethodpost=newPostMethod(uri);
Stringrequest=//createbookingrequestcontent
post.setRequestEntity(newStringRequestEntity(request));
httpClient.executeMethod(post);
if(HttpStatus.SC_CREATED==post.getStatusCode()){
Headerlocation=post.getRequestHeader("Location");
if(location!=null){
System.out.println("Creatednewbookingat:"+location.getValue());
}
}
api文档参考http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/remoting.html#rest-client-access
㈦ JAVA怎么调用接口
String sendPost(String jsonStr, String path)x0dx0a throws IOException {x0dx0a byte[] data = jsonStr.getBytes();x0dx0a java.net.URL url = new java.net.URL(path);x0dx0a java.net.HttpURLConnection conn = x0dx0a (java.net.HttpURLConnection) url.openConnection();x0dx0a conn.setRequestMethod("POST");x0dx0a conn.setConnectTimeout(5 * 1000);// 设置连接超时时间为5秒 x0dx0a conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒 x0dx0a // 使用 URL 连接进行输出,则将 DoOutput标志设置为 truex0dx0a conn.setDoOutput(true);x0dx0a x0dx0a conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");x0dx0a //conn.setRequestProperty("Content-Encoding","gzip");x0dx0a conn.setRequestProperty("Content-Length", String.valueOf(data.length));x0dx0a OutputStream outStream = conn.getOutputStream();// 返回写入到此连接的输出流x0dx0a outStream.write(data);x0dx0a outStream.close();//关闭流x0dx0a String msg = "";// 保存调用http服务后的响应信息x0dx0a // 如果请求响应颂旅码是200,则表示成功x0dx0a if (conn.getResponseCode() == 200) {x0dx0a // HTTP服务端返回的编码坦樱陪是UTF-8,故必须设置为UTF-8,保持编码统一,否则会出现中文乱码x0dx0a BufferedReader in = new BufferedReader(new InputStreamReader(x0dx0a (InputStream) conn.getInputStream(), "UTF-8"));x0dx0a msg = in.readLine();x0dx0a in.close();x0dx0a }x0dx0a conn.disconnect();// 断开连接让蠢x0dx0a return msg;x0dx0a }
㈧ java如何调用对方http接口
你是指发送http请求吗,可以使用Apache 的 HttpClient
//构建HttpClient实例
CloseableHttpClienthttpclient=HttpClients.createDefault();//设置请求超时时间
RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();//指定POST请求
HttpPosthttppost=newHttpPost(url);
httppost.setConfig(requestConfig);//包装请求体
List<NameValuePair>params=newArrayList<NameValuePair>();params.addAll(content);
HttpEntityrequest=newUrlEncodedFormEntity(params,"UTF-8");//发送请求
httppost.setEntity(request);
=httpclient.execute(httppost);//读取响应
HttpEntityentity=httpResponse.getEntity();Stringresult=null;if(entity!=null){
result=EntityUtils.toString(entity,"UTF-8");
}
㈨ java多线程,调用http接口报错,java.net.ConnectException: Connection refused: connect
能成功首先排除防火墙或端口开发问题;
其次确定你连接的端口是否有最大连接数限制(类似mysql有最大连接线程数);
还有就是对应服务的拒绝策略是啥,默认丢弃