我正在对此端点http://httpbin.org/post
发出发布请求,该请求应该返回我发布的发布,该发布应该是String data = "something to post";
,但是我不知道发布请求是否成功。我怎么知道?
这是我正在使用的代码:
public class Post extends AsyncTask <String, String, String>{
@Override
protected String doInBackground(String... strings) {
String urlString = "http://httpbin.org/post"; // URL to call
Log.d("Blyat", urlString);
String data = "something to post"; //data to post
OutputStream out = null;
try {
URL url = new URL(urlString);
Log.d("Post", String.valueOf(url));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());
Log.d("Post", String.valueOf(out));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
Log.d("Post", String.valueOf(urlConnection));
} catch (Exception e) {
System.out.println(e.getMessage());
}
String algo = "blure";
return algo;
}
}
答案 0 :(得分:1)
从URLConnection写入OutputStream后,必须检查连接对象的状态代码。
class Superswag():
def __init__(self, name, where):
self.name = name
self.where = where
class Real(Superswag):
def __init__(self, name, amt_of_buckles):
self.name = name
self.amt_of_buckles = 0
hat = Superswag("hat","head")
jacket = Real("Jacket",10)
def isitcool(object):
if object.name == "coat":
return True
elif object.amt_of_buckles >= 5:
return True
else:
return False
isitcool(hat)
isitcool(jacket)
File "XXXXXXXX", line 16, in isitcool
elif object.amt_of_buckles >= 5:
AttributeError: 'Superswag' object has no attribute 'amt_of_buckles'
如果成功(== 200),则可以通过从Connection的InputStream获取响应来读取响应。
int statusCode = connection.getStatusCode();
通常会从响应中转换为如下字符串:
BufferedReader reader = new BufferedReader(connection.getInputStream());