curl -H "Content-Type: application/json" -X POST --data '[{"a": 4, "b": 5}\]'
\
-u person@email.com:111sdreiwoiewur_y \
http://mysite.website.com/api/v1/A/B/P
我尝试将上面的curl请求转换为scala postRequest。 curl请求成功运行,但代码遇到400错误。
import java.util
import java.util.ArrayList
import com.google.gson.Gson
import org.apache.catalina.util.Base64
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.message.BasicNameValuePair
import org.apache.http.{HttpHeaders, NameValuePair}
case class dummy_information( a:Int, b:Int)
object postTest extends App {
val restUrl="http://mysite.website.com/api/v1/A/B/P"
val TOKEN= "111sdreiwoiewur_y"
val username="person@email.com"
val dummyCaseObj = dummy_information(4,5)
val dummyAsJson: String = new Gson().toJson(dummyCaseObj)
val httpPost: HttpPost = new HttpPost(restUrl)
val base64=username+":"+ TOKEN
val encoding: String =Base64.encode(base64.getBytes("UTF-8"))
httpPost.setHeader(HttpHeaders.AUTHORIZATION,"Basic "+new String(encoding))
httpPost.setHeader(HttpHeaders.ACCEPT,"application/json")
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
//passing payload
httpPost.setEntity(new StringEntity(dummyAsJson))
//POST response
val client = HttpClientBuilder.create().build()
var response = client.execute(httpPost)
println("Response Code : " +response.getStatusLine().getStatusCode())
}
Responsecode
即将400
。我如何更改代码以获得200
响应?
答案 0 :(得分:0)
dummyAsJson在下面的行是JSONObject,curl接受为JSONArray。 httpPost.setEntity(new StringEntity(dummyAsJson))
因此改为上线 httpPost.setEntity(new StringEntity(" [" + dummyAsJson +"]"))