----------------------- GET ----------------------------
String getUrl = "https://github.com/Hyman1993";
URL url = new URL(getUrl);
//connectionのインスタンス
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//リクエストのメソッドを指定
connection.setRequestMethod("GET");
//通信開始
connection.connect();
// レスポンスコードを戻る
int responseCode = connection.getResponseCode();
// レスポンスコードを判断する、OKであれば、進める
if(responseCode == HttpURLConnection.HTTP_OK){
// 通信に成功した
// テキストを取得する
InputStream in= connection.getInputStream();
String encoding = con.getContentEncoding();
if(null == encoding){
encoding = "UTF-8";
}
StringBuffer result = new StringBuffer();
final InputStreamReader inReader = new InputStreamReader(in, encoding);
final BufferedReader bufReader = new BufferedReader(inReader);
String line = null;
// 1行ずつテキストを読み込む
while((line = bufReader.readLine()) != null) {
result.append(line);
}
// クローズ
bufReader.close();
inReader.close();
in.close();
// アウトプット
Log.log("result=============:"+result);
}
---------------------------- POST -----------------------------
String postUrl = "https://github.com/Hyman1993";
URL url = new URL(postUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//POSTに指定
connection.setRequestMethod("POST");
//POST出力可能
connection.setDoOutput(true);
//入力可能
connection.setDoInput(true);
//cache無し
connection.setUseCaches(false);
// データタイプをjsonに指定する
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//コネクション、通信開始
connection.connect();
// jsonデータを出力ストリームへ書き出す
String body = "userName=hyman1993&password=123456";
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(body);
writer.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
// 通信に成功した
// GETメソッドを同様に
}
------------------------------- ファイルのアップロード -------------------------------------------------------
String postUrl = "https://github.com/Hyman1993";
URL url = new URL(postUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "file/*");
connection.connect();
OutputStream outputStream = connection.getOutputStream();
FileInputStream fileInputStream = new FileInputStream("file");
int length = -1;
byte[] bytes = new byte[1024];
while ((length = fileInputStream.read(bytes)) != -1){
outputStream.write(bytes,0,length);
}
fileInputStream.close();
outputStream.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
// 通信に成功した
// GETメソッドを同様に
}