Java的HttpURLConnection类无法连接到ASP.NET API,连接被拒绝 [英] Java HttpURLConnection failed to connect to ASP.NET API, connection refused
问题描述
我尝试使用下面code张贴在Java中的一些数据(在Android Studio中):
公共静态字符串downloadContent(URL网址,ContentValues dataToPost)抛出IOException
InputStream为= NULL;
INT长度= 500;
串contentAsString =; 尝试{
HttpURLConnection的康恩=(HttpURLConnection类)url.openConnection();
conn.setReadTimeout(10000 / *毫秒* /);
conn.setConnectTimeout(15000 / *毫秒* /);
conn.setRequestMethod(GET);
conn.setDoInput(真); 字符串的queryString = getQuery(dataToPost);
conn.connect();
OutputStream的OS = conn.getOutputStream();
INT响应= conn.getResponse code();
但是BufferedWriter作家=新的BufferedWriter(
新OutputStreamWriter(OS,UTF-8));
writer.write(的queryString);
writer.flush();
writer.close();
是= conn.getInputStream();
contentAsString = convertInputStreamToString(是,长度);
}赶上(MalformedURLException的E){
e.printStackTrace();
}赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(的ProtocolException E){
e.printStackTrace();
e.printStackTrace();
}赶上(IOException异常五){
串K = e.getMessage();
} {最后
如果(是!= NULL){
is.close();
}
}
返回contentAsString;
}私人静态字符串getQuery(ContentValues PARAMS)抛出UnsupportedEncodingException {
StringBuilder的结果=新的StringBuilder();
布尔第一= TRUE; 对于(字符串键:params.keySet()){
如果(第一)
第一= FALSE;
其他
result.append(与&); result.append(URLEn coder.en code(键,UTF-8));
result.append(=);
result.append(URLEn coder.en code(params.get(密钥)的ToString(),UTF-8));
} 返回result.toString();
}公共静态字符串convertInputStreamToString(InputStream的流,INT长度)抛出IOException异常,UnsupportedEncodingException {
读卡器读卡器= NULL;
读者=新InputStreamReader的(流,UTF-8);
的char []缓冲区=新的char [长度]
reader.read(缓冲液);
返回新的String(缓冲);
}
和我使用下面code调用downloadContent方式:
(?HTTP://本地主机:59524 / API /测试/ AAA ID = 1) URL U =新的URL;
ContentValues C =新ContentValues();
c.put(ID,1);
NetworkCommunication.downloadContent(U,C);
我也试过网址更改为的http://本地主机:59524 / API /测试/ AAA
和我使用C#(在Visual Studio)所规定的试验一个asp.net MVC API,以及这里的code的API:
公共类的TestController:ApiController
{
的[AcceptVerbs(GET,POST)]
公共IHttpActionResult AAA(INT ID)
{
返回OK(好极了!);
}
}
但是为什么在Android Studio中,该程序无法连接?
java.net.ConnectException:无法连接到本地主机/ 127.0.0.1
(端口59524)15000ms后:ECONNREFUSED(连接被拒绝)
块引用>在
上面抛出IOException异常conn.connect();
预期结果:
在我发布ID为
的http://本地主机:59524 / API /测试/ AAA
,我
应该接受一个字符串好极了!
块引用>解决方案使用SOAP Web服务调用asp.net web服务。
我WebSrevice.java类code
进口org.ksoap2.SoapEnvelope;
进口org.ksoap2.serialization.PropertyInfo;
进口org.ksoap2.serialization.SoapObject;
进口org.ksoap2.serialization.SoapPrimitive;
进口org.ksoap2.serialization.SoapSerializationEnvelope;
进口org.ksoap2.transport.HttpTransportSE;
进口android.R.array;
进口android.util.Log;公共类的WebService {
// web服务的命名空间 - 在WSDL中找到
私人静态字符串NAMESPACE =http://tempuri.org/;
// URL的Webservice - WSDL文件位置
私有静态字符串URL =web服务路径;
//首先确认你更改IP地址
// SOAP动作URI再次命名空间+ Web方法名称
私人静态字符串SOAP_ACTION =http://tempuri.org/;公共静态字符串invokeCategory(字符串webMethName,字符串compId){
串loginStatus =;
//创建请求
SoapObject要求=新SoapObject空间(namespace,webMethName);
//物业持有输入参数 的PropertyInfo compidPI =新的PropertyInfo();
//设置用户名
compidPI.setName(companyid);
//设置值
compidPI.setValue(compId);
//设置的dataType
compidPI.setType(为String.class);
//添加到Request对象的属性
request.addProperty(compidPI); SoapSerializationEnvelope信封=新SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = TRUE;
//设置输出SOAP对象
envelope.setOutputSoapObject(请求);
//创建HTTP调用对象
HttpTransportSE androidHttpTransport =新HttpTransportSE(URL); 尝试{
//调用Web服务
androidHttpTransport.call(SOAP_ACTION + webMethName,信封);
//获取响应
SoapPrimitive响应=(SoapPrimitive)envelope.getResponse();
//指定为布尔变量变量
loginStatus = response.toString(); }赶上(例外五){
//分配错误状态在静态变量真正的错误的
Login.errored = TRUE;
e.printStackTrace();
}
//返回booleam调用对象
返回loginStatus;
}
}我asynchtask类
私有类GetCategoryAndProduct扩展的AsyncTask<弦乐,太虚,太虚>
{
@覆盖
保护无效doInBackground(字符串... PARAMS){
//调用Web方法
数据=(WebService.invokeCategory(的getCategory,COMPANY_ID,0));
返回null;
} @覆盖
//一旦WebService的返回响应
保护无效onPostExecute(虚空结果){
//获取服务器响应这里 }
}
}
@覆盖
在preExecute保护无效(){ }}我的Asp.net web服务code
[WebService的空间(namespace =http://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)公共类Login_Service:System.Web.Services.WebService
{
[的WebMethod]
公共字符串的getCategory(字符串companyid)
{
//编写Web服务code在这里 }
}随意在这里评论
I am trying to use below code to post some data in Java (In Android Studio):
public static String downloadContent(URL url, ContentValues dataToPost) throws IOException { InputStream is = null; int length = 500; String contentAsString = ""; try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); String queryString = getQuery(dataToPost); conn.connect(); OutputStream os = conn.getOutputStream(); int response = conn.getResponseCode(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(queryString); writer.flush(); writer.close(); is = conn.getInputStream(); contentAsString = convertInputStreamToString(is, length); } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); e.printStackTrace(); } catch (IOException e) { String k = e.getMessage(); } finally { if (is != null) { is.close(); } } return contentAsString; } private static String getQuery(ContentValues params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (String key : params.keySet()) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(key, "UTF-8")); result.append("="); result.append(URLEncoder.encode(params.get(key).toString(), "UTF-8")); } return result.toString(); } public static String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[length]; reader.read(buffer); return new String(buffer); }
And I'm calling the downloadContent method using below code:
URL u = new URL("http://localhost:59524/api/Test/AAA?id=1"); ContentValues c = new ContentValues(); c.put("id", "1"); NetworkCommunication.downloadContent(u, c);
I've also tried changing the URL to
http://localhost:59524/api/Test/AAA
And I made an asp.net MVC API using C# (In visual studio) for testing, and here's the code for the API:
public class TestController : ApiController { [AcceptVerbs("GET", "POST")] public IHttpActionResult AAA(int id) { return Ok("Very good!"); } }
I am able to access the API through the browser:
But why in android studio, the program failed to connect?
java.net.ConnectException: failed to connection to localhost/127.0.0.1 (port 59524) after 15000ms: ECONNREFUSED (Connection refused)
The above IOException throws in
conn.connect();
Expected result:
When I post the "ID" to
http://localhost:59524/api/Test/AAA
, I should receive a string "Very good!"
解决方案use Soap webservice to call the asp.net web service.
My WebSrevice.java class code
import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.R.array; import android.util.Log; public class WebService { //Namespace of the Webservice - can be found in WSDL private static String NAMESPACE = "http://tempuri.org/"; //Webservice URL - WSDL File location private static String URL = "webservice path"; //Make sure you changed IP address //SOAP Action URI again Namespace + Web method name private static String SOAP_ACTION = "http://tempuri.org/"; public static String invokeCategory( String webMethName, String compId) { String loginStatus = ""; // Create request SoapObject request = new SoapObject(NAMESPACE, webMethName); // Property which holds input parameters PropertyInfo compidPI = new PropertyInfo(); // Set Username compidPI.setName("companyid"); // Set Value compidPI.setValue(compId); // Set dataType compidPI.setType(String.class); // Add the property to request object request.addProperty(compidPI); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; // Set output SOAP object envelope.setOutputSoapObject(request); // Create HTTP call object HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); try { // Invoke web service androidHttpTransport.call(SOAP_ACTION+webMethName, envelope); // Get the response SoapPrimitive response = (SoapPrimitive) envelope.getResponse(); // Assign it to boolean variable variable loginStatus = response.toString(); } catch (Exception e) { //Assign Error Status true in static variable 'errored' Login.errored = true; e.printStackTrace(); } //Return booleam to calling object return loginStatus; } }
My asynchtask class
private class GetCategoryAndProduct extends AsyncTask<String,Void,Void> { @Override protected Void doInBackground(String... params) { //Call Web Method data =(WebService.invokeCategory("getCategory",company_id,"0")); return null; } @Override //Once WebService returns response protected void onPostExecute(Void result) { //get server response here } } } @Override protected void onPreExecute() { } }
My Asp.net webservice code
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class Login_Service : System.Web.Services.WebService { [WebMethod] public string getCategory(string companyid) { //write your web service code here } }
feel free to comment here
这篇关于Java的HttpURLConnection类无法连接到ASP.NET API,连接被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!